package com.gitee.muii.bilibili.subscribe.jobs

import com.gitee.muii.bilibili.subscribe.entity.DynamicEntity
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.json.Json
import org.quartz.JobExecutionContext
import org.springframework.data.redis.core.HashOperations
import org.springframework.data.redis.core.ValueOperations
import org.springframework.http.HttpEntity
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpMethod
import org.springframework.scheduling.quartz.QuartzJobBean
import org.springframework.stereotype.Service
import org.springframework.util.MultiValueMap
import org.springframework.web.client.RestTemplate

@Service("dynamicJobBean")
class DynamicJob(
    var hashOperations: HashOperations<String, String, String>,
    var valueOperations: ValueOperations<String, String>,
    var restTemplate: RestTemplate
) : QuartzJobBean() {

    @OptIn(ExperimentalSerializationApi::class)
    override fun executeInternal(context: JobExecutionContext) {
        val format = Json {
            ignoreUnknownKeys = true
            coerceInputValues = true
        }
        val cookie: String = valueOperations["cookie"]!!
        val uidTimeStamps: Map<String, String> = hashOperations.entries("uidTimeStamps")
        hashOperations.entries("uids").forEach { (uid, name) ->
            val api = "https://api.bilibili.com/x/polymer/web-dynamic/v1/feed/space?host_mid=$uid"
            try {
                val headers = HttpHeaders()
                headers["Cookie"] = cookie
                val httpHeaders = HttpEntity<MultiValueMap<String, Any>>(headers)
                val data = restTemplate.exchange(api, HttpMethod.GET, httpHeaders, String::class.java).body!!
                val dynamicEntity: DynamicEntity = format.decodeFromString(data)
                var timestamp0: Long? = null
                dynamicEntity.data.items.forEach { item ->
                    val timestamp: Long = item.modules.moduleAuthor.pubTs
                    val uidTimeStamp: Long = uidTimeStamps[uid]?.toLong() ?: 0L
                    if (timestamp > uidTimeStamp && item.type == "DYNAMIC_TYPE_AV") {
                        if (timestamp0 == null) {
                            timestamp0 = timestamp
                        }
                        val key: String = name + "_" + timestamp
                        hashOperations.put(
                            "videos",
                            key,
                            "https://b23.tv/${item.modules.moduleDynamic.major.archive.bvid}"
                        )
                        hashOperations.put("titles", key, item.modules.moduleDynamic.major.archive.title)
                    }
                }
                if (timestamp0 != null) {
                    hashOperations.put("uidTimeStamps", uid, timestamp0.toString())
                }
            } catch (e: Exception) {
                println(e.message)
            }
        }
    }

}
